import java.util.Scanner;
import java.util.regex.Pattern;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.LinkedList;

/**
 * LinesOfCodeCounter provides a method to count the standard lines of code
 * in a java program, given a file name.
 * 
 * Files which are located in the same directory as the compiled java class
 * can be denoted with the file name "file.ext".  However, if the file name
 * is located elsewhere on a PC, you would use the format for the filename:
 * "c:\\folder\\folder\\filename.ext" when you type it in.
 * 
 * @author (Erin Blockley) 
 * @version (v 1.0)
 */
public class LinesOfCodeCounter
{
    // array containing the regular expressions for any line to ignore
    private static String[] regexs = {"^\\s*$", "^\\s*\\{\\s*$", "^\\s*}\\s*$", "^\\s*//.*$", "^\\s*import.*$", "^\\s*package.*$", "^\\s*/\\*.*$", "^\\s*\\*.*$"};
    private static String fileName = "";
    private static File txtFile;
    private static Scanner scan;
    private static int loc = 0;
    private static LinkedList<String> lines = new LinkedList<String>();
    
    /**
     * The main method for the class.  This method has a simple interface
     * to the console, and will request a file name.
     * 
     * @param args  A String array of args
     */
    public static void main(String[] args)
    {
        scan = new Scanner(System.in);
        
        // the user is prompted for a file name
        System.out.println("\nEnter the name of the file:");
        fileName = scan.nextLine();

        // check to see if the file name is valid
        try
        {
            txtFile = new File(fileName);
            scan = new Scanner(txtFile);

            while(scan.hasNextLine())
            {
                // read the content of the file into the linked list
                lines.add(scan.nextLine());
                // increment the number of lines of code, before ignoring any
                loc++;
            }
            scan.close();
            
            for(String s : lines)
            {
                for(int i=0; i<7; i++)
                {
                    // match each stored line to each regular expression
                    if(Pattern.matches(regexs[i],s))
                    {
                        // if any matches are found, ignore the line by
                        // decrementing the count by one
                        loc--;
                    }
                }
            }

            // print the result
            System.out.println(fileName + " is " + loc);
        }
        // if the file name is not valid, an error msg is returned
        catch(FileNotFoundException fnfe)
        {
            System.out.println("File not found.");
        }
    }
}
